import datetime
import logging
import utils
from django.shortcuts import get_object_or_404, render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django import newforms as forms
from django.template import Context, loader
from google.appengine.ext import db
from google.appengine.ext.db import Model
from google.appengine.ext.db import GqlQuery
from google.appengine.api import users
from google.appengine.ext import webapp
from smartwebnote.models import Note


def index(request):
	return HttpResponse('Hello world')

def signout(request):
	return HttpResponseRedirect(users.create_logout_url("/"))

def anonymous_list(request):
	user = users.get_current_user()
	if user:
		return list(request)
	else:
		query = GqlQuery("SELECT * FROM Note WHERE user = :user ORDER BY last_updated DESC, created DESC", user=user)
		return render_to_response('smartwebnote/anonymous_note_list.html',
									{'object_list':query.fetch(1000)})	
	
def check_permission(handler_method):
	def check_login(self, *args):
		user = users.get_current_user()
		if user:
			logging.info('valid user: ' + user.nickname())	
			return handler_method(self, *args)
		else:
			logging.info('invalid user')
			redirectUrl = users.create_login_url("/list")
			logging.info(redirectUrl)
			return HttpResponseRedirect(redirectUrl)			
	return check_login

@check_permission    
def list(request):	
	user = users.get_current_user()
	query = GqlQuery("SELECT * FROM Note WHERE user = :user ORDER BY last_updated DESC, created DESC", user=user)
	return render_to_response('smartwebnote/note_list.html',
								{'object_list':query.fetch(1000)})


def delete(request, object_key, model, template_name, post_delete_redirect):
	if request.method == 'POST':
		Model.delete(Model.get(object_key))
		return HttpResponseRedirect(post_delete_redirect)
	else:
		note = get_object_or_404(model, object_key)
		return render_to_response(template_name, {'object':note})

class NoteEditorForm(forms.Form):
	content = forms.CharField(widget=forms.Textarea())	


def edit(request, object_key, model, template_name, post_save_redirect):
	if request.method == 'POST':
		# Update the note content here
		form = NoteEditorForm(request.POST)
		if form.is_valid():
			content = form.clean_data['content']
			note = Model.get(object_key)
			note.content = content
			note.title = title_from_content(content)
			note.save()
			logging.info('note saved '+ str(datetime.datetime.now()))
			logging.info('note last_updated '+ str(note.last_updated))
		return HttpResponseRedirect(post_save_redirect)
	else:
		note = get_object_or_404(model, object_key)
		# update the last_visited field
		# note.save(), we should use a different mechnism to track this
		form = NoteEditorForm(initial={'content': note.content})
		return render_to_response(template_name, {'object':note, 'form': form})				
	
def create(request, model, template_name, post_save_redirect):
	if request.method == 'POST':
		pass
	else:
		# Create a new Note and redirect to Edit
		logging.info('/create GET')
		note = model()
		user = users.get_current_user()
		note.user = user
		note.title = 'New Note'
		key = str(note.put())
		logging.debug('new note is created:' + key)
		return HttpResponseRedirect('/edit/'+key)
		#return render_to_response(template_name, {'form': form})	
		
def title_from_content(content):
	logging.debug('title_from_content')
	textonly = utils.strip_tags(content)
	#logging.info('textonly:'+textonly)
	title = textonly[0:50].strip()
	logging.info('title:'+title)
	return title
	
''' Experiment for using POST to pass information 
'''

def save(request, object_key, model, template_name, post_save_redirect):
	if request.method == 'POST':
		logging.info('/save POST')
		if (request.POST):
			logging.info('key= ' + request.POST.get('key'))
			logging.info('content= ' + request.POST.get('content'))
		return HttpResponseRedirect(post_save_redirect)
	else:
		logging.info('/save GET')
		for key in request.GET.lists():
			logging.info (key)
		#logging.info('request.GET ' + request.GET.get('a'))
		#return HttpResponseRedirect(post_save_redirect)		
		
		
def xmllist(request):
	return render_to_response_xml('smartwebnote/xml/note_list.xml',
								{'object_list':query.order('-last_updated')})	
def xmlcreate(request, model):
	if request.method == 'POST':	
		logging.info('xmlcreate.POST')
		if (request.POST):
			logging.info('content= ' + request.POST.get('content'))		
			content = request.POST.get('content')
			note = model()
			note.content = content
			note.title = title_from_content(content)
			logging.info('title_from_content returns successfully: '+ note.title)
			key = str(note.put())
			if (note.is_saved()):
				logging.info('note is saved. key=' + key)
			return HttpResponse('<xml><key>'+key+'</key></xml>')
	else:
		pass

def xmledit(request, object_key, model):
	if request.method == 'POST':
		# Update the note content here
		note = Model.get(object_key)
		'''
		note.content = content
		note.title = title_from_content(content)
		note.save()
		'''
		logging.info('note saved '+ str(datetime.datetime.now()))
		logging.info('note last_updated '+ str(note.last_updated))
		return HttpResponseRedirect(post_save_redirect)
	else:
		note = get_object_or_404(model, object_key)
		return render_to_response_xml('smartwebnote/xml/note_edit.xml', {'object':note})	

def render_to_response_xml (template_name, context):
		t = loader.get_template(template_name)
		c = Context(context)
		r = HttpResponse(t.render(c),
			mimetype="application/xhtml+xml")	
		return r;	